﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using Dashboard.ProductBonus.Business;
using System.Globalization;

namespace Dashboard.ProductBonus
{
    public partial class FormWorkingShift : Form
    {
        public FormWorkingShift()
        {
            InitializeComponent();
        }

        private void toolStripButtonQuery_Click(object sender, EventArgs e)
        {
            this.DoQuery();
        }

        private void toolStripButtonCreate_Click(object sender, EventArgs e)
        {
            using (FormWorkingShiftAdd wsa = new FormWorkingShiftAdd())
            {
                wsa.ShowDialog(this);

                this.DoQuery();
            }
        }

        private DateTime ConvertToDateTime(string hourMinutes)
        {
            int hour = int.Parse(hourMinutes.Split(':')[0]);
            int minute = int.Parse(hourMinutes.Split(':')[1]);

            return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minute, 0);
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            this.ultraGridMain.UpdateData();

            try
            {
                this.Cursor = Cursors.WaitCursor;

                DataTable result;
                WorkingShift ws = new WorkingShift();
                foreach (UltraGridRow row in this.ultraGridMain.Rows)
                {
                    int id = Convert.ToInt32(row.Cells["Id"].Value);
                    string code = Convert.ToString(row.Cells["Code"].Value);
                    string description = Convert.ToString(row.Cells["Description"].Value);

                    DateTime fromTime = this.ConvertToDateTime(row.Cells["FromTime"].Text);
                    DateTime toTime = this.ConvertToDateTime(row.Cells["ToTime"].Text);

                    if (ws.CalculateTotalTime(fromTime, toTime) <= 2)
                    {
                        if (MessageBox.Show(this, "Total time is smaller than 2 hours, are you sure to continue?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                        {
                            row.Selected = true;
                            return;
                        }
                    }

                    result = ws.GetWorkingShiftById(id);

                    if (result.Rows.Count == 0)
                    {
                        // 不可能出现这个Case,但还是会考虑一下
                        // Do Nothing
                    }
                    else
                    {
                        if (this.ConvertToDateTime(result.Rows[0]["FromTime"].ToString()).ToString("HH:mm") == fromTime.ToString("HH:mm") &&
                            this.ConvertToDateTime(result.Rows[0]["ToTime"].ToString()).ToString("HH:mm") == toTime.ToString("HH:mm") &&
                            Convert.ToString(result.Rows[0]["Description"]) == description)
                        {
                            continue;
                        }

                        if (this.ConvertToDateTime(result.Rows[0]["FromTime"].ToString()).ToString("HH:mm") == fromTime.ToString("HH:mm") &&
                            this.ConvertToDateTime(result.Rows[0]["ToTime"].ToString()).ToString("HH:mm") == toTime.ToString("HH:mm") &&
                            Convert.ToString(result.Rows[0]["Description"]) != description)
                        {
                            ws.UpdateWorkingShift(id, description, fromTime, toTime, true);
                            continue;
                        }

                        if (this.ConvertToDateTime(result.Rows[0]["FromTime"].ToString()).ToString("HH:mm") != fromTime.ToString("HH:mm") ||
                            this.ConvertToDateTime(result.Rows[0]["ToTime"].ToString()).ToString("HH:mm") != toTime.ToString("HH:mm"))
                        {
                            // 当前数据设置为InValid
                            ws.UpdateWorkingShift(id, Convert.ToString(result.Rows[0]["Description"]), this.ConvertToDateTime(result.Rows[0]["FromTime"].ToString()), this.ConvertToDateTime(result.Rows[0]["ToTime"].ToString()), false);

                            result = ws.GetWorkingShift(id, code, fromTime, toTime);
                            if (result.Rows.Count == 0)
                            {
                                // 新增一笔记录
                                ws.AddNewWorkingShift(code, description, fromTime, toTime, true);
                            }
                            else
                            {
                                // 将原本的记录重置为Valid
                                ws.UpdateWorkingShift(int.Parse(result.Rows[0]["Id"].ToString()), description, fromTime, toTime, true);
                            }
                        }
                    }
                }

                MessageBox.Show(this, "Save successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.DoQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            this.ultraGridMain.UpdateData();

            List<int> selectedIds = new List<int>();
            WorkingShift ws = new WorkingShift();

            foreach (UltraGridRow row in this.ultraGridMain.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value) == true)
                {
                    if (ws.IsWorkingShiftUsed(Convert.ToInt32(row.Cells["Id"].Value)))
                    {
                        MessageBox.Show(this, "Working shift [" + Convert.ToString(row.Cells["Code"].Value) + "] is already in use, can not be deleted.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    selectedIds.Add(Convert.ToInt32(row.Cells["Id"].Value));
                }
            }

            if (selectedIds.Count == 0)
            {
                MessageBox.Show(this, "No data selected.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show(this, "Are you sure to delete selected records?", "Confirm",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    foreach (int id in selectedIds)
                    {
                        ws.DeleteWorkingShiftById(id);
                    }

                    MessageBox.Show(this, "Delete successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    this.DoQuery();
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormWorkingShift_Load(object sender, EventArgs e)
        {
            this.DoQuery();
        }

        private void DoQuery()
        {
            DataTable dt = new WorkingShift().GetValidWorkingShiftList();

            this.ultraGridMain.DataSource = dt;
            this.ultraGridMain.DataBind();
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            e.Layout.Bands[0].ScrollTipField = "Code";

            // 隐藏不需要显示的列
            e.Layout.Bands[0].Columns["Id"].Hidden = true;

            e.Layout.Bands[0].Columns["Code"].CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
            e.Layout.Bands[0].Columns["FromTime"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["ToTime"].CellActivation = Activation.AllowEdit;

            e.Layout.Bands[0].Columns["FromTime"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["ToTime"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["Description"].CellClickAction = CellClickAction.EditAndSelectText;

            e.Layout.Bands[0].Columns["FromTime"].Header.Appearance.ForeColor = Color.Red;
            e.Layout.Bands[0].Columns["ToTime"].Header.Appearance.ForeColor = Color.Red;
            e.Layout.Bands[0].Columns["Description"].Header.Appearance.ForeColor = Color.Red;
        }
    }
}
